package com.example.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.PageRequest;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/list")
    public Map<String, Object> list(@RequestBody(required = false) PageRequest pageRequest, 
                                    @RequestParam(defaultValue = "") String name,
                                    @RequestParam(defaultValue = "") String mobile) {
        if (pageRequest == null) {
            pageRequest = new PageRequest();
        }
        
        Page<User> page = new Page<>(pageRequest.getPageNum(), pageRequest.getPageSize());
        Page<User> result = userService.findPage(page, name, mobile);
        
        Map<String, Object> response = new HashMap<>();
        response.put("total", result.getTotal());
        response.put("users", result.getRecords());
        return response;
    }

    @PostMapping("/findById")
    public User findById(@RequestBody Map<String, Integer> request) {
        Integer id = request.get("id");
        return userService.findById(id);
    }

    @PostMapping("/save")
    public boolean save(@RequestBody User user) {
        return userService.saveUser(user);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @PostMapping("/delete")
    public boolean delete(@RequestBody Map<String, Integer> request) {
        Integer id = request.get("id");
        return userService.deleteById(id);
    }
}